"""
verify that old knowledge base references are removed and new one is used
test knowledge base replacement functionality
"""
import sys
from pathlib import Path

# Add project root to Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

import logging
from src.llm.hiagent_app.services.agent_knowledge_service import AgentKnowledgeService
from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.config.hiagent_config import HiAgentConfig

# configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def get_agent_info(api_client, agent_id, workspace_id):
    """get agent basic info and configuration"""
    try:
        # Get basic info
        body = {
            "WorkspaceID": workspace_id,
            "AppID": agent_id
        }
        brief_response = api_client.make_request("GetAppBrief", body)
        brief_info = brief_response.get("AppBriefInfo", {})

        # Get configuration
        config_response = api_client.make_request("GetAppConfigDraft", body)
        config = config_response.get("AppConfigDraft", {})

        return {
            "name": brief_info.get("Name"),
            "description": brief_info.get("Description"),
            "knowledge_ids": config.get("KnowledgeIDs", []),
            "rag_enabled": config.get("ModelConfig", {}).get("RagEnabled"),
            "model_id": config.get("ModelID")
        }
    except Exception as e:
        logger.error(f"Failed to get agent info: {str(e)}")
        return None


def test_knowledge_base_replacement():
    """test that old KB is removed and new KB is used"""
    logger.info("=" * 60)
    logger.info("Test: Knowledge Base Replacement")
    logger.info("=" * 60)

    api_client = HiAgentAPIClient()
    service = AgentKnowledgeService()
    workspace_id = HiAgentConfig.DEFAULT_WORKSPACE_ID
    source_agent_id = "d3tjsrvi96maquv5k8v0"

    logger.info(f"Source Agent ID: {source_agent_id}")
    logger.info(f"Workspace ID: {workspace_id}")

    # Step 1: Get source agent info
    logger.info("\nStep 1: Getting source agent info...")
    source_info = get_agent_info(api_client, source_agent_id, workspace_id)

    if not source_info:
        logger.error("Failed to get source agent info")
        return False

    logger.info(f"Source Agent Name: {source_info['name']}")
    logger.info(f"Source Agent Knowledge IDs: {source_info['knowledge_ids']}")
    logger.info(f"Source Agent Model ID: {source_info['model_id']}")

    # Step 2: Create new agent with new name and new KB
    logger.info("\nStep 2: Creating new agent with new name and new KB...")

    new_agent_name = "test_kb_replacement"
    new_kb_name = "test_kb_replacement_knowledge"

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name=new_agent_name,
            knowledge_name=new_kb_name,
            agent_description="test knowledge base replacement",
            workspace_id=workspace_id,
            source_agent_id=source_agent_id
        )
        logger.info(f"New Agent ID: {agent_id}")
        logger.info(f"New Knowledge ID: {knowledge_id}")
    except Exception as e:
        logger.error(f"Failed to create agent: {str(e)}")
        return False

    # Step 3: Get new agent info
    logger.info("\nStep 3: Getting new agent info...")
    new_info = get_agent_info(api_client, agent_id, workspace_id)

    if not new_info:
        logger.error("Failed to get new agent info")
        # Cleanup
        service._cleanup_resources(agent_id, knowledge_id, workspace_id)
        return False

    logger.info(f"New Agent Name: {new_info['name']}")
    logger.info(f"New Agent Knowledge IDs: {new_info['knowledge_ids']}")
    logger.info(f"New Agent Model ID: {new_info['model_id']}")

    # Step 4: Verify requirements
    logger.info("\n" + "=" * 60)
    logger.info("Verification Results")
    logger.info("=" * 60)

    all_checks_passed = True

    # Check 1: Name changed
    if new_info['name'] == new_agent_name:
        logger.info(f"✓ Agent name changed to: {new_agent_name}")
    else:
        logger.error(f"✗ Agent name NOT changed")
        logger.error(f"  Expected: {new_agent_name}")
        logger.error(f"  Got: {new_info['name']}")
        all_checks_passed = False

    # Check 2: Old knowledge base removed
    source_kb_ids = set(source_info['knowledge_ids'])
    new_kb_ids = set(new_info['knowledge_ids'])

    if source_kb_ids and source_kb_ids.intersection(new_kb_ids):
        logger.error(f"✗ Old knowledge base references NOT removed")
        logger.error(f"  Source KB IDs: {source_kb_ids}")
        logger.error(f"  New KB IDs: {new_kb_ids}")
        logger.error(f"  Overlap: {source_kb_ids.intersection(new_kb_ids)}")
        all_checks_passed = False
    else:
        logger.info(f"✓ Old knowledge base references removed")
        logger.info(f"  Source KB IDs: {source_kb_ids if source_kb_ids else 'None'}")
        logger.info(f"  New KB IDs: {new_kb_ids}")

    # Check 3: New knowledge base used
    if knowledge_id in new_info['knowledge_ids']:
        logger.info(f"✓ New knowledge base is configured: {knowledge_id}")
    else:
        logger.error(f"✗ New knowledge base NOT configured")
        logger.error(f"  Expected KB ID: {knowledge_id}")
        logger.error(f"  Configured KB IDs: {new_info['knowledge_ids']}")
        all_checks_passed = False

    # Check 4: Only new knowledge base (no extras)
    if new_info['knowledge_ids'] == [knowledge_id]:
        logger.info(f"✓ ONLY new knowledge base configured (no extras)")
    else:
        logger.warning(f"⚠ Multiple knowledge bases configured")
        logger.warning(f"  Expected: [{knowledge_id}]")
        logger.warning(f"  Got: {new_info['knowledge_ids']}")

    # Check 5: RAG enabled
    if new_info['rag_enabled']:
        logger.info(f"✓ RAG is enabled")
    else:
        logger.error(f"✗ RAG is NOT enabled")
        all_checks_passed = False

    # Check 6: Model ID preserved
    if new_info['model_id'] == source_info['model_id']:
        logger.info(f"✓ Model ID preserved: {new_info['model_id']}")
    else:
        logger.warning(f"⚠ Model ID changed")
        logger.warning(f"  Source: {source_info['model_id']}")
        logger.warning(f"  New: {new_info['model_id']}")

    # Cleanup
    logger.info("\nCleaning up test resources...")
    service._cleanup_resources(agent_id, knowledge_id, workspace_id)

    return all_checks_passed


def main():
    """main test function"""
    logger.info("Starting knowledge base replacement verification")
    logger.info("=" * 60)

    result = test_knowledge_base_replacement()

    logger.info("\n" + "=" * 60)
    logger.info("Final Test Result")
    logger.info("=" * 60)

    if result:
        logger.info("✓ ALL CHECKS PASSED")
        logger.info("\nSummary:")
        logger.info("1. ✓ Agent name changed to specified name")
        logger.info("2. ✓ Old knowledge base references removed")
        logger.info("3. ✓ New knowledge base configured")
        logger.info("4. ✓ Configuration from source preserved")
    else:
        logger.error("✗ SOME CHECKS FAILED")
        logger.error("\nPlease review the verification results above")


if __name__ == "__main__":
    main()
